import { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { useTheme } from "@/hooks/useTheme";
import { AuthContext } from "@/App";
import { cn } from "@/lib/utils";
import { motion } from "framer-motion";
import { z } from "zod";
import { toast } from "sonner";
import UserService from "@/services/user";



const loginSchema = z.object({
  account: z.string().min(3, "账号长度至少3位"),
  password: z.string().min(5, "密码长度至少5位")
});

export default function Login() {
  const navigate = useNavigate();
  const { theme, toggleTheme, isDark } = useTheme();
  const { isAuthenticated, logout, setUserInfo } = useContext(AuthContext);
  const [formData, setFormData] = useState({
    account: "",
    password: "",
    remember: false
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrors({});
    
    try {
      const validation = loginSchema.safeParse({
        account: formData.account,
        password: formData.password
      });

      if (!validation.success) {
        const errorMap: Record<string, string> = {};
        validation.error.issues.forEach(issue => {
          errorMap[issue.path[0]] = issue.message;
        });
        setErrors(errorMap);
        return;
      }

      // 调用真实登录接口
      const res = await UserService.login({
        account: formData.account,
        password: formData.password
      });

      if (formData.remember) {
        localStorage.setItem("rememberedAccount", formData.account);
      }
      
      // 获取用户信息
      const userInfoRes = await UserService.getUserInfo();
      const userInfo = userInfoRes || {};
      const { teamList = [], projectList = [], ...userData } = userInfo.data || {};
      
      // 设置默认选中的团队和项目
      const defaultTeam = teamList.length > 0 ? teamList[0].teamId : null;
      const defaultProject = projectList.length > 0 ? projectList[0].projectId : null;
      
      // 更新上下文
      setUserInfo({
        ...userData,
        teamList,
        projectList
      });
      
      // 持久化数据
      localStorage.setItem("userInfo", JSON.stringify({
        ...userData,
        teamList,
        projectList
      }));
      if (defaultTeam) {
        localStorage.setItem("currentTeam", defaultTeam);
      }
      if (defaultProject) {
        localStorage.setItem("currentProject", defaultProject);
      }
      
      toast.success("登录成功");
      navigate("/team-list");
    } catch (error: any) {
      console.error('登录错误:', error);
      toast.error(
        <div className="space-y-1">
          <div className="font-medium">登录失败</div>
          <div className="text-sm">{error.message}</div>
        </div>,
        { duration: 5000 }
      );
      
      // 如果是网络错误，显示更多帮助信息
      if (error.message.includes('网络连接') || error.message.includes('服务器') || error.message.includes('跨域')) {
        toast.info(
          <div className="space-y-1">
            <div className="font-medium">帮助提示</div>
            <div className="text-sm">
              1. 请检查网络连接<br/>
              2. 确认服务器地址: https://apiiot.hongyanyun.cn<br/>
              3. 如果是跨域问题，请联系管理员检查:<br/>
              - 服务器CORS配置是否允许当前域名: {window.location.origin}<br/>
              - 服务器是否支持OPTIONS预检请求<br/>
              - 服务器是否正确返回以下头信息:<br/>
                * Access-Control-Allow-Origin: {window.location.origin}<br/>
                * Access-Control-Allow-Methods: POST, OPTIONS<br/>
                * Access-Control-Allow-Headers: Authorization, Content-Type<br/>
                * Access-Control-Allow-Credentials: true<br/>
              4. 如果是开发环境，可以尝试:<br/>
                - 使用代理服务器绕过CORS限制<br/>
                - 临时禁用浏览器安全限制(仅限开发)
            </div>
          </div>,
          { duration: 15000 }
        );
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={cn(
      "min-h-screen flex flex-col bg-transparent",
      isDark ? "text-gray-100" : "text-gray-900"
    )}>
      {/* 简化导航栏 */}
      <header className={cn(
        "sticky top-0 z-10 p-2 border-b",
        isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-2">
            <i className="fa-solid fa-file-code text-2xl text-blue-500"></i>
            <h1 className="font-mono font-bold text-xl">API Docs</h1>
          </div>
              {isAuthenticated ? (
                <button 
                  onClick={() => logout()}
                  className={cn(
                    "px-3 py-1 rounded-md text-sm font-mono mr-2",
                    isDark ? "bg-red-600 hover:bg-red-700" : "bg-red-500 hover:bg-red-600",
                    "text-white"
                  )}
                >
                  <i className="fa-solid fa-right-from-bracket mr-1"></i>
                  退出
                </button>
              ) : null}
              <button 
                onClick={toggleTheme}
                className={cn(
                  "w-10 h-10 rounded-full flex items-center justify-center",
                  isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                )}
              >
                <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
              </button>
        </div>
      </header>

      {/* 登录表单 */}
      <main className="flex-1 flex items-center justify-center p-4">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className={cn(
            "w-full max-w-md p-8 rounded-xl shadow-lg",
            isDark ? "bg-gray-800" : "bg-white"
          )}
        >
          <h2 className="font-mono font-bold text-2xl mb-6 text-center">用户登录</h2>
          
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="account" className="block font-mono text-sm mb-1">
                账号
              </label>
              <div className="relative">
                <input
                  type="text"
                  id="account"
                  name="account"
                  value={formData.account}
                  onChange={handleChange}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2 transition-all",
                      errors.account 
                      ? "border-red-500 focus:ring-red-500" 
                      : isDark 
                        ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                        : "border-gray-300 focus:ring-orange-500 bg-white",
                    "placeholder-gray-400"
                  )}
                  placeholder="请输入账号"
                />
                {errors.account && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 text-red-500">
                    <i className="fa-solid fa-circle-exclamation"></i>
                  </div>
                )}
              </div>
              {errors.account && (
                <p className="mt-1 text-sm text-red-500">{errors.account}</p>
              )}
            </div>

            <div>
              <label htmlFor="password" className="block font-mono text-sm mb-1">
                密码
              </label>
              <div className="relative">
                <input
                  type="password"
                  id="password"
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2 transition-all",
                    errors.password 
                      ? "border-red-500 focus:ring-red-500" 
                      : isDark 
                        ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                        : "border-gray-300 focus:ring-orange-500 bg-white",
                    "placeholder-gray-400"
                  )}
                  placeholder="••••••••"
                />
                {errors.password && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 text-red-500">
                    <i className="fa-solid fa-circle-exclamation"></i>
                  </div>
                )}
              </div>
              {errors.password && (
                <p className="mt-1 text-sm text-red-500">{errors.password}</p>
              )}
            </div>

            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="remember"
                  name="remember"
                  checked={formData.remember}
                  onChange={handleChange}
                  className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <label htmlFor="remember" className="ml-2 font-mono text-sm">
                  记住我
                </label>
              </div>
              <a 
                href="#" 
                className={cn(
                  "font-mono text-sm hover:underline",
                  isDark ? "text-blue-400" : "text-orange-500"
                )}
                onClick={(e) => {
                  e.preventDefault();
                  toast.info("功能开发中");
                }}
              >
                忘记密码?
              </a>
            </div>

            <motion.button
              type="submit"
              whileTap={{ scale: 0.98 }}
              disabled={isLoading}
              className={cn(
                "w-full py-2 px-4 rounded-md font-medium flex items-center justify-center",
                "transition-colors duration-200",
                isDark 
                  ? "bg-blue-600 hover:bg-blue-700" 
                  : "bg-orange-500 hover:bg-orange-600",
                "text-white"
              )}
            >
              {isLoading ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                  登录中...
                </>
              ) : (
                "登录"
              )}
            </motion.button>
          </form>
          
          <div className="mt-4 text-center">
            <motion.button
              onClick={() => navigate('/register')}
              className={cn(
                "text-sm font-mono hover:underline",
                isDark ? "text-blue-400" : "text-blue-500"
              )}
              whileHover={{ scale: 1.05 }}
            >
              没有账号？立即注册
            </motion.button>
          </div>
        </motion.div>
      </main>
    </div>
  );
}
